package com.bigdata.service.impl;

import com.bigdata.dao.NWQualityMapper;
import com.bigdata.entity.NWQuality;
import com.bigdata.entity.NWQualityVO;
import com.bigdata.service.NWQualityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class NWQualityServiceImpl implements NWQualityService {

    private final NWQualityMapper nwQualityMapper;

    @Override
    public NWQualityVO getNetworkQualityStats() {
        try {
            // 获取数据
            List<NWQuality> stats = nwQualityMapper.getNetworkQualityStats();
            log.info("查询到的原始数据: {}", stats);
            
            if (stats == null || stats.isEmpty()) {
                log.warn("未查询到数据");
                return createEmptyResult();
            }
            
            // 构建返回数据
            NWQualityVO result = new NWQualityVO();
            
            // 设置图例（运营商）
            result.setLegends(Arrays.asList("CMCC", "CUCC", "CTCC"));
            
            // 设置X轴数据（网络制式）
            result.setXAxisData(Arrays.asList("4G", "3G", "2G"));
            
            // 处理数据系列
            List<List<Double>> seriesData = new ArrayList<>();
            
            // 为每个运营商处理数据
            for (String operator : Arrays.asList("CMCC", "CUCC", "CTCC")) {
                List<Double> operatorData = new ArrayList<>();
                for (String nwType : Arrays.asList("4G", "3G", "2G")) {
                    Double value = stats.stream()
                        .filter(s -> s.getNwOperator().equals(operator) && s.getNwType().equals(nwType))
                        .map(NWQuality::getSpeed)
                        .findFirst()
                        .orElse(0.0);
                    operatorData.add(value);
                }
                seriesData.add(operatorData);
                log.info("运营商 {} 的数据: {}", operator, operatorData);
            }
            
            result.setSeriesData(seriesData);
            result.setUnit("Mbps");
            
            return result;
            
        } catch (Exception e) {
            log.error("获取网络质量统计数据失败", e);
            throw new RuntimeException("获取网络质量统计数据失败: " + e.getMessage());
        }
    }

    private NWQualityVO createEmptyResult() {
        NWQualityVO result = new NWQualityVO();
        result.setLegends(Arrays.asList("CMCC", "CUCC", "CTCC"));
        result.setXAxisData(Arrays.asList("4G", "3G", "2G"));
        result.setSeriesData(Arrays.asList(
            Arrays.asList(0.0, 0.0, 0.0),
            Arrays.asList(0.0, 0.0, 0.0),
            Arrays.asList(0.0, 0.0, 0.0)
        ));
        result.setUnit("Mbps");
        return result;
    }
}